<?php
namespace Common\Controller;
use Think\Controller;
use Common\Model\PriceModel;
use Common\Model\TradeBuyModel;
use Common\Model\TradeSellModel;
use Common\Model\TradeDealModel;
use Common\Model\UserMoneyModel;
class CommonController extends ValidateController {
    public $return_type;
    public function __construct()
    {
        parent::__construct();
        $this->return_type='ajax';
    }
    public function getVerify($id)
    {
        $Verify =     new \Think\Verify();
        $Verify->fontSize = 70;
        $Verify->length   = 6;
        $Verify->useNoise = true;
        $Verify->useImgBg = true;
        $Verify->codeSet = '0123456789';
        $Verify->fontttf = '5.ttf';
        return $Verify->entry($id);
    }
    protected function checkVierify($code, $id)
    {
        $verify = new \Think\Verify();
        return $verify->check($code, $id);
    }
    protected function getCountry()
    {
        $data=M('Country')->select();
        foreach ($data as $k=>$v)
        {
            $datas[$v['id']]=$v;
        }
        return $datas;
    }
    protected function getBankType()
    {
        $data=M('BankType')->select();
        foreach ($data as $k=>$v)
        {
            $datas[$v['id']]=$v;
        }
        return $datas;
    }
	/**
	 * 文件上传方法
	 * @param string $name 传入图片的name
	 * @return boolean
	 */
	protected function uploadOne($name){
		$upload = new \Think\Upload();// 实例化上传类
		$upload->maxSize   =     3145728 ;// 设置附件上传大小
		$upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
		// 		$upload->mimes      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
		$upload->rootPath  =      './Uploads/'; // 设置附件上传根目录
		$upload->saveName = $name.'_'.time().'_'.rand(100000,999999);
		// 上传单个文件
		$info   =   $upload->uploadOne($_FILES[$name]);
		if(!$info) {// 上传错误提示错误信息
			$data['info']=$upload->getError();
			$data['status']=false;
			return $data;
		}else{// 上传成功 获取上传文件信息
			$data['info']='/Uploads/'.$info['savepath'].$info['savename'];
			$data['status']=true;
			return $data;
		}
	}
    protected function tradeBuyBegin($user_id,$num,$buy_currency,$sell_currency)
    {
        $price_model=PriceModel::newSelf();
        while ($num>0)
        {
            $now_price=$price_model->findNowBuyPrice();
            if ($num>$now_price['num']) {
                $num2=$now_price['num'];
                $this->tradeBuyCore($user_id, $num2, $buy_currency, $sell_currency);
                $price_model->where(['id'=>$now_price['id']])->setInc('buy_num',$num2);
                $num=$num-$num2;
            }else {
                $this->tradeBuyCore($user_id, $num, $buy_currency, $sell_currency);
                $price_model->where(['id'=>$now_price['id']])->setInc('buy_num',$num);
                $num=0;
            }
            
        }
        return true;
    }
    protected function tradeBuyBeginByMoney($user_id,$money,$buy_currency,$sell_currency)
    {
        $price_model=PriceModel::newSelf();
        $now_price=$price_model->findNowBuyPrice();
        $money_model=UserMoneyModel::newSelf();
        while ($money>$now_price['price'])
        {
            $num=floor($money/$now_price['price']);
            if ($num>$now_price['num']-$now_price['buy_num']) {
                $num=$now_price['num']-$now_price['buy_num'];
                $this->tradeBuyCore($user_id, $num, $buy_currency, $sell_currency);
            }else {
                $this->tradeBuyCore($user_id, $num, $buy_currency, $sell_currency);
            }
            $money=$money-$num*$now_price['price'];
            $price_model->where(['id'=>$now_price['id']])->setInc('buy_num',$num);
            $now_price=$price_model->findNowBuyPrice();
            
        }
        return true;
    }
    protected function tradeBuyCore($user_id,$num,$buy_currency,$sell_currency)
    {
        $price_model=PriceModel::newSelf();
        $now_price=$price_model->findNowBuyPrice();
        $data['user_id']=$user_id;
        $data['add_time']=time();
        $data['status']=0;
        $data['price']=$now_price['price'];
        $data['num']=$num;
        $data['surplus_num']=$num;
        
        $buy_model=TradeBuyModel::newSelf();
        $buy_id=$buy_model->add($data);
        $sell_model=TradeSellModel::newSelf();
        $deal_model=TradeDealModel::newSelf();
        $money_model=UserMoneyModel::newSelf();
        
        $res=$money_model->decUserMoney($user_id, $buy_currency['id'],$num*$now_price['price']);
        while ($num>0)
        {
            $sell_order=$sell_model->findOneByConductAndPrice($now_price['price']);
            if (!$sell_order) {
                break;
            }
            $need_num=min($num,$sell_order['surplus_num']);
            if ($need_num>=$sell_order['surplus_num']) {
                $sell_model->where(['id'=>$sell_order['id']])->setField('surplus_num',0);
                $sell_model->where(['id'=>$sell_order['id']])->setField('status',1);
                if ($need_num==$sell_order['surplus_num']) {
                    $buy_model->where(['id'=>$buy_id])->setField('status',1);
                }
            }else {
                $sell_model->where(['id'=>$sell_order['id']])->setDec('surplus_num',$need_num);
                $buy_model->where(['id'=>$buy_id])->setField('status',1);
            }
            
            $buy_model->where(['id'=>$buy_id])->setDec('surplus_num',$need_num);
            $num-=$need_num;
            
            
            $money_model->incUserMoney($user_id, $sell_currency['id'], $need_num);
            $money_model->incUserMoney($sell_order['user_id'], $buy_currency['id'], $need_num*$now_price['price']);
            
            $price_model->where(['id'=>$now_price['id']])->setDec('sell_num',$need_num);
            $price_model->where(['id'=>$now_price['id']])->setDec('buy_num',$need_num);
            
            $price_model->where(['id'=>$now_price['id']])->setDec('num',$need_num);
            
            $data['sell_id']=$buy_id;
            $data['buy_id']=$sell_order['id'];
            $data['num']=$need_num;
            $data['price']=$now_price['price'];
            $data['add_time']=time();
            $deal_model->add($data);
        }

        $price_model->where('num<=0')->setField('status',1);
        return $res;
    }
    protected function tradeSellBegin($user_id,$num,$buy_currency,$sell_currency)
    {
        $price_model=PriceModel::newSelf();
        while ($num>0)
        {
            $now_price=$price_model->findNowSellPrice();
            if ($num>$now_price['num']-$now_price['sell_num']) {
                $num2=$now_price['num']-$now_price['sell_num'];
                $this->tradeSellCore($user_id, $num2, $buy_currency, $sell_currency,$now_price['price']);
                $price_model->where(['id'=>$now_price['id']])->setInc('sell_num',$num2);
                $num=$num-$num2;
            }else {
                $this->tradeSellCore($user_id, $num, $buy_currency, $sell_currency,$now_price['price']);
                $price_model->where(['id'=>$now_price['id']])->setInc('sell_num',$num);
                $num=0;
            }
            $res=UserMoneyModel::newSelf()->decUserMoney($user_id, $sell_currency,$num);
            
        }
        return true;
        
    }
    protected function tradeSellCore($user_id,$num,$buy_currency,$sell_currency,$price)
    {
        $price_model=PriceModel::newSelf();
        $now_price=$price_model->findNowPrice();
        $data['user_id']=$user_id;
        $data['add_time']=time();
        $data['status']=0;
        $data['price']=$price;
        $data['num']=$num;
        $data['surplus_num']=$num;

        $sell_model=TradeSellModel::newSelf();
        $sell_id=$sell_model->add($data);
        if ($price!=$now_price['price']) {
            return $sell_id;;
        }
        
        
        $buy_model=TradeBuyModel::newSelf();
        $deal_model=TradeDealModel::newSelf();
        $money_model=UserMoneyModel::newSelf();

        while ($num>0)
        {
            $buy_order=$buy_model->findOneByConductAndPrice($now_price['price']);
            if (!$buy_order) {
                break;
            }
            $need_num=min($num,$buy_order['surplus_num']);
            if ($need_num>=$buy_order['surplus_num']) {
                $buy_model->where(['id'=>$buy_order['id']])->setField('surplus_num',0);
                $buy_model->where(['id'=>$buy_order['id']])->setField('status',1);
                if ($need_num==$buy_order['surplus_num']) {
                    $sell_model->where(['id'=>$sell_id])->setField('status',1);
                }
            }else {
                $buy_model->where(['id'=>$buy_order['id']])->setDec('surplus_num',$need_num);
                $sell_model->where(['id'=>$sell_id])->setField('status',1);
            }
            
            $sell_model->where(['id'=>$sell_id])->setDec('surplus_num',$need_num);
            $num-=$need_num;

            $money_model->incUserMoney($user_id, $sell_currency['id'], $need_num*$now_price['price']);
            $money_model->incUserMoney($buy_order['user_id'], $buy_currency['id'], $need_num);

            $price_model->where(['id'=>$now_price['id']])->setDec('sell_num',$need_num);
            $price_model->where(['id'=>$now_price['id']])->setDec('buy_num',$need_num);
            $price_model->where(['id'=>$now_price['id']])->setDec('num',$need_num);
            
            $data['sell_id']=$sell_id;
            $data['buy_id']=$buy_order['id'];
            $data['num']=$need_num;
            $data['price']=$now_price['price'];
            $data['add_time']=time();
            $deal_model->add($data);
            
        }

        
//         $new_now_price=$price_model->findNowPrice();
//         if ($now_price['price']!=$new_now_price['price']) {
//             $price_model->where(['id'=>$now_price['id']])->setField('status',1);
//         }
        return true;
    }
}